package com.food.foodapi.controller;

import com.food.foodapi.instans.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.UUID;

/**
 * @author 92110
 */
@RestController
public class FileUploadController {

    @Value("${file.upload-dir}")
    private String uploadDir;
    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/file/upload")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 创建目标目录（如果不存在）
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成唯一文件名
            String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();

            // 保存文件
            Path targetPath = Paths.get(uploadDir, fileName);
            file.transferTo(targetPath);

            // 获取本机IP地址
            InetAddress localhost = InetAddress.getLocalHost();
            String hostAddress = localhost.getHostAddress();
            // 访问地址
            String accessUrl = "http://" + hostAddress + ":" + serverPort + "/api/images/";
            // 返回访问地址
            String fileUrl = accessUrl + fileName;
            return Result.success(fileUrl);
        } catch (IOException e) {
            return Result.error("文件上传失败");
        }
    }
}
